﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PPIDesktopClient.Entities;
using PPIProxy;
using System.IO;
using System.Data;
using VMind.Global;
using PPIMobileInterface.Entities;
using PPIDesktopClient.General;
using VMind.Global;


namespace PPIDesktopClient.Logic
{
    public class LVendor_Visit_XMissionStructures_Image
    {
        #region CRUD

        public static int Save(EVendor_Visit_XMissionStructures_Image image)
        {
            if (image.Id == Int32.MinValue)
            {
                image.Id = Insert(image);
                return image.Id;
            }
            else
            {
                Update(image);
                return 0;
            }

        }

        private static int Insert(EVendor_Visit_XMissionStructures_Image image)
        {
            ConfigReader _ConfigReader = ConfigReader.GetInstance();
            int _FreeIdInsert = LVendor_Visit_XMissionStructures_Image.GetFreePosition(image.Id, image.Asset.Id);
            int _NewImageServerID;

            if (_FreeIdInsert == 0)
            {

                if (image.File.Exists)
                {
                    byte[] _ImageBytes = EVendor_Visit_XMissionStructures_Image.ToBytes(image.File.FullName);
                    image.FileName = image.File.Name;
                    _NewImageServerID = WVendor_Visit_XMissionStructures_Image.Insert(image.Asset.Id, image.SolutionAvailable, image.FileName, _ImageBytes, image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, image.Pole.Id, _ConfigReader.GetConnectionString());
                    image.Id = _NewImageServerID;
                    if(image.Pole.Id != Int32.MinValue)
                        UpdatePoleReference(image);
                }
                else
                {
                    _NewImageServerID = 0;
                    //TODO
                }

            }
            else
            {
                image.Id = _FreeIdInsert;
                UpdatePoleReference(image);
                _NewImageServerID = _FreeIdInsert;
            }

            //byte[] _ImageBytes = EVendor_Visit_XMissionStructures_Image.ToBytes(_File.FullName);
            //image.Filename = _File.Name;
            //_NewImageServerID = DVendor_Visit_XMissionStructures_Image.Insert(image.Vendor_Visit_XMissionStructure.Vendor_Visit_XMissionStructureId, image.SolutionAvailable, image.Filename, _ImageBytes, image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, image.Vendor_Visit_XMissionStructures_Pole.Vendor_Visit_XMissionStructures_PoleId);

            return _NewImageServerID;
        }

        public static int Update(EVendor_Visit_XMissionStructures_Image image)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            int _FreeIdInsert = 0;

            //Verify Pole

            if (image.Id != null)
            {
                if (image.Pole.Id != Int32.MinValue)
                {
                    _FreeIdInsert = LVendor_Visit_XMissionStructures_Image.GetFreePosition(image.Id, image.Asset.Id);
                    if (_FreeIdInsert == 0)
                    {
                        if (!VerifyExistence(image.Id, image.Pole.Id, image.Asset.Id))
                        {
                            //insert Row via SQL.
                            WVendor_Visit_XMissionStructures_Image.InsertExistingImage(image.SolutionAvailable, "", image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, image.Pole.Id, image.Id,_Reader.GetConnectionString());
                        }
                    }
                    else
                    {
                        image.Id = _FreeIdInsert;
                        UpdatePoleReference(image);
                        //_NewImageServerID = _FreeIdInsert;
                    }
                }
                else
                {
                    UpdatePoleReference(image);
                    //_NewImageServerID = _FreeIdInsert;
                }
            }
            return 0;
        }

        public static void Delete(EVendor_Visit_XMissionStructures_Image image)
        {
            try
            {
                ConfigReader _Reader = ConfigReader.GetInstance();
                DesasocciatePole(image);
                WVendor_Visit_XMissionStructures_Image.Delete(image.Id,_Reader.GetConnectionString());
                if (image.File.Exists)
                    image.File.Delete();
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "LVendor_Visit_XMissionStructures_Image.Delete() " + ex.Source, ex.Message, ex.StackTrace);
            }
        }

        public static void DesasocciatePole(EVendor_Visit_XMissionStructures_Image image)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            WVendor_Visit_XMissionStructures_Image.UpdatePoleReference(image.SolutionAvailable, image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, Int32.MinValue, image.Id,_Reader.GetConnectionString());
        }

        public static void UpdatePoleReference(EVendor_Visit_XMissionStructures_Image image)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            WVendor_Visit_XMissionStructures_Image.UpdatePoleReference(image.SolutionAvailable, image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, image.Pole.Id, image.Id,_Reader.GetConnectionString());
        }

        #endregion CRUD

        #region Query

        public static List<EVendor_Visit_XMissionStructures_Image> GetByStructureID(int structureID, DataTable ImagesData)
        {
            EVendor_Visit_XMissionStructures_Image _Image;
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (DataRow _ImageData in ImagesData.Rows)
            {
                #region Images
                _Image = new EVendor_Visit_XMissionStructures_Image();
                _Image.Id = VMind.Global.ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructures_ImageId"]);
                _Image.Direction = ConvertHelper.Todouble(_ImageData["Direction"]);
                _Image.Latitude = ConvertHelper.Todouble(_ImageData["Latitude"]);
                _Image.Longitude = ConvertHelper.Todouble(_ImageData["Longitude"]);
                _Image.Altitude = ConvertHelper.Todouble(_ImageData["Altitude"]);
                _Image.SatelliteCount = ConvertHelper.Toint(_ImageData["SatelliteCount"]);
                _Image.SatelliteTime = ConvertHelper.ToDateTime(_ImageData["SatelliteTime"]);
                _Image.SolutionAvailable = ConvertHelper.Tobool(_ImageData["SolutionAvailable"]);
                _Image.FileName = ConvertHelper.Tostring(_ImageData["Filename"]);
                _Image.Asset = new EVendor_Visit_XMissionStructure(structureID);
                _Image.Pole = new EVendor_Visit_XMissionStructures_Pole(ConvertHelper.Toint(_ImageData["Vendor_Visit_XMissionStructures_PoleFK"]));
                _Image.File = GetImageFile(_Image.Asset.Id, _Image.FileName);
                #endregion Images
                if (!_Images.Contains(_Image))
                    _Images.Add(_Image);


            }
            return _Images;
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetByStructureID(int structureID, List<EVendor_Visit_XMissionStructures_Image> imageList)
        {
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (EVendor_Visit_XMissionStructures_Image i in imageList)
            {
                if (i.Asset.Id == structureID)
                    _Images.Add(i);
            }
            return _Images;
        }

        public static void AssignImagesToStructure(EBaseAsset structure, List<EVendor_Visit_XMissionStructures_Image> images)
        {
            foreach (EBaseImage i in images)
            {
                if (i.Asset.Id == structure.Id)
                {
                    if (!structure.Images.Contains(i))
                    {
                        structure.Images.Add(i);
                    }
                }
            }
        }

        public static void AssignImagesToPole(EBasePole pole, List<EVendor_Visit_XMissionStructures_Image> images)
        {
            foreach (EBaseImage i in images)
            {
                if (i.Pole.Id != Int32.MinValue)
                {
                    if (pole.Id == i.Pole.Id)
                    {
                        if(!pole.Images.Contains(i))
                            pole.Images.Add(i);
                    }
                }
            }
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetByPoleID(int poleID, DataTable imageDataTable)
        {
            EVendor_Visit_XMissionStructures_Image _Image;
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (DataRow _ImageRow in imageDataTable.Rows)
            {
                if (poleID == VMind.Global.ConvertHelper.Toint(_ImageRow["Vendor_Visit_XMissionStructures_PoleFK"]))
                {
                    #region Images
                    _Image = new EVendor_Visit_XMissionStructures_Image();
                    _Image.Id = ConvertHelper.ToInt32(_ImageRow["Vendor_Visit_XMissionStructures_ImageId"]);
                    _Image.Direction = ConvertHelper.Todouble(_ImageRow["Direction"]);
                    _Image.Latitude = ConvertHelper.Todouble(_ImageRow["Latitude"]);
                    _Image.Longitude = ConvertHelper.Todouble(_ImageRow["Longitude"]);
                    _Image.Altitude = ConvertHelper.Todouble(_ImageRow["Altitude"]);
                    _Image.SatelliteCount = ConvertHelper.Toint(_ImageRow["SatelliteCount"]);
                    _Image.SatelliteTime = ConvertHelper.ToDateTime(_ImageRow["SatelliteTime"]);
                    _Image.SolutionAvailable = ConvertHelper.Tobool(_ImageRow["SolutionAvailable"]);
                    _Image.FileName = ConvertHelper.Tostring(_ImageRow["Filename"]);
                    _Image.Asset = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_ImageRow["Vendor_Visit_XMissionStructureFK"]));
                    _Image.File = GetImageFile(_Image.Asset.Id, _Image.FileName);
                    _Image.Pole = new EVendor_Visit_XMissionStructures_Pole(ConvertHelper.Toint(_ImageRow["Vendor_Visit_XMissionStructures_PoleFK"]));
                    #endregion Images
                    _Images.Add(_Image);
                }
            }
            return _Images;
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetByPoleID(int poleID, List<EVendor_Visit_XMissionStructures_Image> imageList)
        {
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (EVendor_Visit_XMissionStructures_Image i in imageList)
            {
                if (i.Pole.Id != Int32.MinValue)
                {
                    if (poleID == i.Pole.Id)
                    {
                        _Images.Add(i);
                    }
                }
            }
            return _Images;
        }

        public static DataTable GetDataTableByStructureID(int structureID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            return WVendor_Visit_XMissionStructures_Image.GetByStructureID(structureID,_Reader.GetConnectionString()).Tables[0];
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetByStructure(int structureID)
        {
            DataTable _ImagesDatatable = GetDataTableByStructureID(structureID);


            EVendor_Visit_XMissionStructures_Image _Image;
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (DataRow _ImageData in _ImagesDatatable.Rows)
            {
                #region Images
                _Image = new EVendor_Visit_XMissionStructures_Image();
                _Image.Id = VMind.Global.ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructures_ImageId"]);
                _Image.Direction = ConvertHelper.Todouble(_ImageData["Direction"]);
                _Image.Latitude = ConvertHelper.Todouble(_ImageData["Latitude"]);
                _Image.Longitude = ConvertHelper.Todouble(_ImageData["Longitude"]);
                _Image.Altitude = ConvertHelper.Todouble(_ImageData["Altitude"]);
                _Image.SatelliteCount = ConvertHelper.Toint(_ImageData["SatelliteCount"]);
                _Image.SatelliteTime = ConvertHelper.ToDateTime(_ImageData["SatelliteTime"]);
                _Image.SolutionAvailable = ConvertHelper.Tobool(_ImageData["SolutionAvailable"]);
                _Image.FileName = ConvertHelper.Tostring(_ImageData["Filename"]);
                _Image.Asset = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructureFK"]));
                _Image.File = _Image.GetLocalPath();
                _Image.Pole = new EVendor_Visit_XMissionStructures_Pole(ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructures_PoleFK"]));
                #endregion Images
                if (!_Images.Contains(_Image))
                    _Images.Add(_Image);
            }
            return _Images;
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetServerImages(int offset)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            DataTable _ImagesDatatable = WVendor_Visit_XMissionStructures_Image.GetServerImages(offset,_Reader.GetConnectionString()).Tables[0];


            EVendor_Visit_XMissionStructures_Image _Image;
            List<EVendor_Visit_XMissionStructures_Image> _Images = new List<EVendor_Visit_XMissionStructures_Image>();
            foreach (DataRow _ImageData in _ImagesDatatable.Rows)
            {
                #region Images
                _Image = new EVendor_Visit_XMissionStructures_Image();
                _Image.Id = VMind.Global.ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructures_ImageId"]);
                _Image.Direction = ConvertHelper.Todouble(_ImageData["Direction"]);
                _Image.Latitude = ConvertHelper.Todouble(_ImageData["Latitude"]);
                _Image.Longitude = ConvertHelper.Todouble(_ImageData["Longitude"]);
                _Image.Altitude = ConvertHelper.Todouble(_ImageData["Altitude"]);
                _Image.SatelliteCount = ConvertHelper.Toint(_ImageData["SatelliteCount"]);
                _Image.SatelliteTime = ConvertHelper.ToDateTime(_ImageData["SatelliteTime"]);
                _Image.SolutionAvailable = ConvertHelper.Tobool(_ImageData["SolutionAvailable"]);
                _Image.FileName = ConvertHelper.Tostring(_ImageData["Filename"]);
                _Image.File = GetImageFile(ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructureFK"]), ConvertHelper.Tostring(_ImageData["Filename"]));
                _Image.Asset = new EVendor_Visit_XMissionStructure(ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructureFK"]));
                _Image.Pole = new EVendor_Visit_XMissionStructures_Pole(ConvertHelper.ToInt32(_ImageData["Vendor_Visit_XMissionStructures_PoleFK"]));
                #endregion Images
                if (!_Images.Contains(_Image))
                    _Images.Add(_Image);
            }
            return _Images;
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetServerImages()
        {
            return GetServerImages(0);
        }

        private static FileInfo GetImageFile(int structureID, string fileName)
        {
            string _DestinationImagePath;
            _DestinationImagePath = PPIDesktopClient.General.DirHelper.CreateVisitDirectory(structureID, PPIDesktopClient.General.Constants.K_ImageCachePath) + Path.DirectorySeparatorChar + fileName;

            return new FileInfo(_DestinationImagePath);
        }

        public static List<EVendor_Visit_XMissionStructures_Image> GetImagesFromMobileImages(List<EImage> ImagesMobile)
        {
            List<EVendor_Visit_XMissionStructures_Image> _ImagesList = new List<EVendor_Visit_XMissionStructures_Image>();
            EVendor_Visit_XMissionStructures_Image _Image;
            foreach (EImage imageMobile in ImagesMobile)
            {
                _Image = new EVendor_Visit_XMissionStructures_Image();
                _Image.Altitude = imageMobile.Altitude;
                _Image.Latitude = imageMobile.Latitude;
                _Image.Longitude = imageMobile.Longitude;
                _Image.SatelliteCount = imageMobile.SatelliteCount;
                _Image.SatelliteTime = imageMobile.SatelliteTime;
                _Image.SolutionAvailable = imageMobile.SolutionAvailable;
                _Image.StructureServerID = imageMobile.StructureServerID;
                _Image.PoleServerId = imageMobile.PoleServerID;
                _Image.Asset = new EVendor_Visit_XMissionStructure(imageMobile.StructureServerID);
                _Image.Pole = new EVendor_Visit_XMissionStructures_Pole(imageMobile.PoleServerID);
                _Image.Id = imageMobile.ImageId;
                _Image.FileName = imageMobile.Filename;
                _ImagesList.Add(_Image);
            }
            return _ImagesList;
        }

        public static bool VerifyExistence(int imageId, int poleId, int structureID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            int returnValue = WVendor_Visit_XMissionStructures_Image.VerifyExistence(imageId, poleId, structureID,_Reader.GetConnectionString());
            return (returnValue > 0);
        }

        public static int GetFreePosition(int imageId, int structureID)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            int _ReturnValue;
            if (imageId == Int32.MinValue)
                _ReturnValue = WVendor_Visit_XMissionStructures_Image.GetFreePosition(0, structureID,_Reader.GetConnectionString());
            else
                _ReturnValue = WVendor_Visit_XMissionStructures_Image.GetFreePosition(imageId, structureID,_Reader.GetConnectionString());
            return _ReturnValue;
        }

        public static int GetTotal()
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            return WVendor_Visit_XMissionStructures_Image.GetTotal(_Reader.GetConnectionString());
        }

        #endregion

        #region Desktop Query

        public static int CountImagesInDesktop(string folderPath)
        {
            int _TotalImages = 0;
            DirectoryInfo _ImageFolder = new DirectoryInfo(folderPath);
            DirectoryInfo[] _ImagesSubFolders = _ImageFolder.GetDirectories();

            foreach (DirectoryInfo  d in _ImagesSubFolders)
            {
                _TotalImages += d.GetFiles("*.jpg").Length;
                _TotalImages += d.GetFiles("*.jpeg").Length;
            }
            return _TotalImages;
        
        }

        #endregion

        #region Upload

        public static int UploadImage(EVendor_Visit_XMissionStructures_Image image, string imagePath)
        {
            ConfigReader _ConfigReader = ConfigReader.GetInstance();
            Int32 _NewImageServerID = 0;

            byte[] _ImageBytes = EVendor_Visit_XMissionStructures_Image.ToBytes(imagePath);

            try
            {
                _NewImageServerID =
                PPIProxy.WVendor_Visit_XMissionStructures_Image.Insert(image.StructureServerID, image.SolutionAvailable,
                                                                   image.FileName, _ImageBytes, image.Latitude,
                                                                   image.Altitude, image.Longitude,
                                                                   image.SatelliteTime, image.SatelliteCount,
                                                                   image.Direction, image.Pole.Id,
                                                                   _ConfigReader.GetConnectionString());
                //_NewImageServerID = DVendor_Visit_XMissionStructures_Image.Insert(image.StructureServerID, image.SolutionAvailable, image.FileName, _ImageBytes, image.Latitude, image.Altitude, image.Longitude, image.SatelliteTime, image.SatelliteCount, image.Direction, image.Pole.Id,_ConfigReader.GetConnectionString());

                image.Id = _NewImageServerID;

                PPIProxy.WVendor_Visit_XMissionStructures_Image.SaveFile(image.GetWebserviceFile(), _ImageBytes);
                
                return _NewImageServerID;

            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        #endregion
    }
}
